{extend name="layout/iframe_layout" /}

{block name="title"}创建新表{/block}
{block name="style"}
<style>
.crud-generator {
  padding: 20px;
}

.columns-config {
  margin: 20px 0;
}

.option-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.draggable-column {
  cursor: move;
  padding: 10px;
  margin-bottom: 5px;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.draggable-column:hover {
  background-color: #e9eef5;
}

.draggable-column .el-form-item {
  margin-bottom: 10px;
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.drag-handle {
  cursor: move;
  color: #909399;
}

.delete-column {
  cursor: pointer;
  color: #f56c6c;
}

.table-config {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
}
</style>
{/block}

{block name="content"}

<div id="app" >
    <div class="crud-generator">
    <el-form :model="config" label-width="150px">
      <!-- 表配置 -->
      <div class="table-config">
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 表名输入 -->
            <el-form-item label="表名" required>
              <el-input
                v-model="config.tableName"
                placeholder="请输入表名包含前缀，如:bs_order"
                style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 表注释 -->
            <el-form-item label="表注释">
              <el-input
                v-model="config.tableComment"
                placeholder="请输入表注释"
                style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 字符集选择 -->
            <el-form-item label="字符集">
              <el-select v-model="config.charset" placeholder="请选择字符集" style="width: 300px;">
                <el-option label="utf8mb4" value="utf8mb4"></el-option>
                <el-option label="utf8" value="utf8"></el-option>
                <el-option label="gbk" value="gbk"></el-option>
                <el-option label="latin1" value="latin1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 排序规则 -->
            <el-form-item label="排序规则">
              <el-select v-model="config.collation" placeholder="请选择排序规则" style="width: 300px;">
                <el-option label="utf8mb4_unicode_ci" value="utf8mb4_unicode_ci"></el-option>
                <el-option label="utf8mb4_general_ci" value="utf8mb4_general_ci"></el-option>
                <el-option label="utf8_unicode_ci" value="utf8_unicode_ci"></el-option>
                <el-option label="utf8_general_ci" value="utf8_general_ci"></el-option>
                <el-option label="gbk_chinese_ci" value="gbk_chinese_ci"></el-option>
                <el-option label="gbk_bin" value="gbk_bin"></el-option>
                <el-option label="latin1_swedish_ci" value="latin1_swedish_ci"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 字段配置 -->
      <div class="columns-config">
        <el-button type="primary" @click="addColumn" size="small" icon="el-icon-plus">添加字段</el-button>

        <draggable v-model="columns" tag="div" handle=".drag-handle">
          <div v-for="(column, index) in columns" :key="index" class="draggable-column">
            <div class="column-header">
              <i class="el-icon-rank drag-handle"></i>
              <i class="el-icon-delete delete-column" @click="deleteColumn(index)"></i>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="字段名" required>
                  <el-input v-model="column.field" placeholder="字段名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="类型" required>
                  <el-select v-model="column.type" placeholder="请选择类型" style="width: 100%;" @change="onTypeChange(column)">
                    <el-option label="INT" value="INT"></el-option>
                    <el-option label="VARCHAR" value="VARCHAR"></el-option>
                    <el-option label="TEXT" value="TEXT"></el-option>
                    <el-option label="DATE" value="DATE"></el-option>
                    <el-option label="DATETIME" value="DATETIME"></el-option>
                    <el-option label="TINYINT" value="TINYINT"></el-option>
                    <el-option label="SMALLINT" value="SMALLINT"></el-option>
                    <el-option label="MEDIUMINT" value="MEDIUMINT"></el-option>
                    <el-option label="BIGINT" value="BIGINT"></el-option>
                    <el-option label="FLOAT" value="FLOAT"></el-option>
                    <el-option label="DOUBLE" value="DOUBLE"></el-option>
                    <el-option label="DECIMAL" value="DECIMAL"></el-option>
                    <el-option label="CHAR" value="CHAR"></el-option>
                    <el-option label="TINYTEXT" value="TINYTEXT"></el-option>
                    <el-option label="MEDIUMTEXT" value="MEDIUMTEXT"></el-option>
                    <el-option label="LONGTEXT" value="LONGTEXT"></el-option>
                    <el-option label="TIME" value="TIME"></el-option>
                    <el-option label="TIMESTAMP" value="TIMESTAMP"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="长度">
                  <el-input v-model="column.length" placeholder="长度"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="小数点">
                  <el-input v-model="column.decimal" placeholder="小数点"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="是否NULL">
                  <el-select v-model="column.nullable" placeholder="是否NULL" style="width: 100%;">
                    <el-option label="NULL" value="NULL"></el-option>
                    <el-option label="NOT NULL" value="NOT NULL"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="键">
                  <el-select v-model="column.key" placeholder="键类型" style="width: 100%;">
                    <el-option label="无" value=""></el-option>
                    <el-option label="PRIMARY KEY" value="PRIMARY KEY"></el-option>
                    <el-option label="UNIQUE" value="UNIQUE"></el-option>
                    <el-option label="INDEX" value="INDEX"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="无符号(数值)">
                  <el-select v-model="column.unsigned" placeholder="是否无符号" style="width: 100%;" :disabled="!isNumericType(column.type)">
                    <el-option label="否" value=""></el-option>
                    <el-option label="是" value="UNSIGNED"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="自增">
                  <el-select v-model="column.autoIncrement" placeholder="是否自增" style="width: 100%;" :disabled="column.key !== 'PRIMARY KEY'">
                    <el-option label="否" value=""></el-option>
                    <el-option label="是" value="AUTO_INCREMENT"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="注释">
                  <el-input v-model="column.comment" placeholder="注释"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="默认值">
                  <el-input v-model="column.default" placeholder="默认值"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </draggable>
      </div>

      <!-- 生成按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleGenerate" :loading="isGenerating">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
{/block}

{block name="script"}
<script src="/static/lib/sortablejs/Sortable.min.js"></script>
<script src="/static/lib/vuedraggable/vuedraggable.umd.min.js"></script>
<script>
  var api_base = '/curd';
  new Vue({
    el: '#app',
    components: {
      draggable: window.vuedraggable
    },
    data() {
      return {
        config: {
          tableName: '',
          tableComment: '',
          charset: 'utf8mb4',
          collation: 'utf8mb4_unicode_ci'
        },
        columns: [],
        isLoading: false,
        isGenerating: false
      };
    },
    methods: {
      addColumn() {
        this.columns.push({
          field: '',
          type: 'VARCHAR',
          length: '255',
          decimal: '',
          nullable: 'NULL',
          key: '',
          comment: '',
          default: '',
          unsigned: '',
          autoIncrement: ''
        });
      },
      deleteColumn(index) {
        this.columns.splice(index, 1);
      },
      isNumericType(type) {
        const numericTypes = ['INT', 'TINYINT', 'SMALLINT', 'MEDIUMINT', 'BIGINT', 'FLOAT', 'DOUBLE', 'DECIMAL'];
        return numericTypes.includes(type);
      },
      onTypeChange(column) {
        // 如果类型改变了，重置无符号和自增选项
        column.unsigned = '';
        column.autoIncrement = '';

        // 根据类型设置默认长度
        switch(column.type) {
          case 'VARCHAR':
            column.length = '255';
            break;
          case 'CHAR':
            column.length = '10';
            break;
          case 'INT':
            column.length = '';
            break;
          case 'TINYINT':
            column.length = '';
            break;
          case 'SMALLINT':
            column.length = '';
            break;
          case 'MEDIUMINT':
            column.length = '';
            break;
          case 'BIGINT':
            column.length = '';
            break;
          case 'FLOAT':
            column.length = '';
            break;
          case 'DOUBLE':
            column.length = '';
            break;
          case 'DECIMAL':
            column.length = '10';
            column.decimal = '2';
            break;
          default:
            column.length = '';
            column.decimal = '';
        }
      },
      // 保存数据表
      async handleGenerate() {
        if (!this.config.tableName) {
          this.$message.error('请输入表名')
          return
        }
        if (this.columns.length === 0) {
          this.$message.error('请先添加字段')
          return
        }
        this.isGenerating = true
        try {
          const config = {
            tableName: this.config.tableName,
            tableComment: this.config.tableComment,
            charset: this.config.charset,
            collation: this.config.collation,
            columns: this.columns
          }
          console.log(config)
          await post(api_base+'/create_table_save',config)
            .then(res => {
              console.log('create_table_save',res)
              if (res.code === 0) {
                this.$message.success('创建成功')
              }else if(res.code === -100){
                //需要二次确认
                this.$confirm('已存在同名表名，是否覆盖？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    // 确定覆盖
                   config.overwrite = true
                    post(api_base+'/create_table_save',config)
                    .then(res => {
                      console.log('create_table_save',res)
                      if (res.code === 0) {
                        this.$message.success('创建成功')
                      }else {
                        this.$message.error(res.msg)
                      }
                    })
                  }).catch(() => {
                    // 取消覆盖
                    this.$message.info('已取消覆盖')
                })
              } else {
                this.$message.error(res.msg)
              }
            })
          // 这里可以添加下载生成的代码或其他后续处理
        } catch (error) {
          console.error('创建失败:', error)
          this.$message.error('操作失败，请检查网络或联系管理员')
        } finally {
          this.isGenerating = false
        }
      }
    },
    mounted() {
    }
  });
</script>
{/block}
